<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/8/5
 * Time: 3:09 PM
 */
namespace app\backend\modules\sys\services;

use app\common\models\Nav;
use app\common\models\NavMenu;

class NavService
{
    public function getList($params){
        $query = Nav::site()->select();
        if($params['name']){
            $query->where('name','like','%'.$params['name'].'%');
        }
        $list = $query
            ->orderBy('id', 'desc')
            ->paginate(10);
        return $list;
    }
    public function query($kwd){
        $list = Nav::site()->select(['id','name']);
        if($kwd){
            $list = $list->where('name','like','%'.$kwd.'%');
        }
        $list = $list
            ->orderBy('id', 'desc')
            ->take(1000)
            ->get();
        return $list;
    }
    public function getMenuList($params){
        $query = NavMenu::site()->select();
        if($params['nav_id']){
            $query->where('nav_id',$params['nav_id']);
        }
        $list = $query
            ->orderBy('display_order', 'desc')
            ->orderBy('id', 'desc')
            ->get();
        $res = [];
        foreach ($list as $v){
            if(!$v['pid']){
                //一级菜单
                $v['pname'] = '一级菜单';
                array_push($res,$v);
            }
        }
        foreach ($res as $k => $v) {
            $res[$k]['sub_menu'] = self::getSubMenu($list, $v['id'],$v['name']);
        }
        return $res;
    }

    public static function getSubMenu(&$list,$pid,$pname){
        $res = [];
        foreach ($list as $k => $v) {
            if ($v['pid'] == $pid) {
                unset($list[$k]);
                $v['pname'] = $pname;
                $v['sub_menu'] = static::getSubMenu($list, $v['id'],$v['name']);
                if (empty($v['sub_menu'])) {
                    unset($v['sub_menu']);
                }
                $res[] = $v;
            }
        }
        return $res;
    }
}